package cn.edu.nwpu.warehousemanagement.util;

import java.util.Map;

/**
 * ThreadLocalUtil 工具类
 * 在LoginInterceptor中设置用户claims信息到ThreadLocal中，在Service中获取用户信息
 * 感觉可能会有点问题（泛型和类型转换），所以直接指定为Map<String, Object>类型
 *
 * @author Loadstar
 * @version 1.0
 */
public class ThreadLocalUtil {
    //提供ThreadLocal对象
//    private static final ThreadLocal<> THREAD_LOCAL = new ThreadLocal();
    private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL = new ThreadLocal<>();

    //根据键获取值
//    public static <T> T get() {
//        return (T) THREAD_LOCAL.get();
//    }
    public static Map<String, Object> get() {
        return THREAD_LOCAL.get();
    }

    //存储键值对
//    public static void set(Object value) {
//        THREAD_LOCAL.set(value);
//    }
    public static void set(Map<String, Object> value) {
        THREAD_LOCAL.set(value);
    }

    //清除ThreadLocal 防止内存泄漏
    public static void remove() {
        THREAD_LOCAL.remove();
    }

    public static Long getLoginUserId() {
        Map<String, Object> tlMap = ThreadLocalUtil.get();
        Object idObj = tlMap.get("id");
        return (idObj instanceof Integer)
                ? ((Integer) idObj).longValue()
                : (Long) idObj;
    }

}